package xyz.quanguanjia.masterboy.groupDetail;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;

import java.util.ArrayList;
import java.util.HashMap;

import xyz.quanguanjia.masterboy.MBDApplication;
import xyz.quanguanjia.masterboy.MBDGroupDetailModel;
import xyz.quanguanjia.masterboy.MBDHttpClient;
import xyz.quanguanjia.masterboy.MBDModelResponse;
import xyz.quanguanjia.masterboy.MBDToolbarUtils;
import xyz.quanguanjia.masterboy.R;
import xyz.quanguanjia.masterboy.ServiceType;
import xyz.quanguanjia.masterboy.adapter.GroupDetailAdapter;
import xyz.quanguanjia.masterboy.adapter.MBDGroupCommentsModel;
import xyz.quanguanjia.masterboy.util.StringUtils;

public class MBDGroupDetailActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    private EditText commentEt;
    private ImageView likeIv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_detail);
        Toolbar toolbar = findViewById(R.id.toolbar);
        commentEt = findViewById(R.id.comment_et);
        MBDToolbarUtils.setCenterTitle(toolbar, "详情");
        MBDToolbarUtils.backButtonClicked(toolbar, new Runnable() {
            @Override
            public void run() {
                finish();
            }
        });
//        MBDToolbarUtils.toolButtonClicked(toolbar, R.id.img_toolbar_more, new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                MBDGroupDetailActivity.this.showActionSheet();
//            }
//        });
        this.recyclerView = findViewById(R.id.recyclerView_group_detail);
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                commentEt.setText("");
                commentEt.setHint("写评论...");
                mMBDGroupCommentsModel = null;
                hideSoftKeyboard();
                return false;
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(MBDApplication.getContext());
        recyclerView.setLayoutManager(layoutManager);
        this.refreshData(0);
        commentEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN)) {
                    // 处理发送逻辑
                    String inputText = commentEt.getText().toString();
                    if (!StringUtils.isNull(inputText)) {
                        hideSoftKeyboard();
                        if (null == mMBDGroupCommentsModel) {
                            sentComment();
                        } else {
                            sentCommentReply();
                        }
                    }
                    return true; // 表示事件已处理
                }
                return false; // 表示事件未处理
            }
        });
        likeIv = findViewById(R.id.group_like_iv);
        likeIv.setAlpha(!StringUtils.isNull(detail.isLike) && detail.isLike.equals("1") ? 1f : 0.5f);
        likeIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //点赞
                like();
            }
        });
    }

    // 打开软键盘的方法
    private void showInputMethodManager() {
        commentEt.requestFocus();
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null && commentEt.requestFocus()) {
            inputMethodManager.showSoftInput(commentEt, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    // 隐藏软键盘的方法
    private void hideSoftKeyboard() {
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    private MBDGroupDetailModel detail;
    private MBDGroupCommentsModel mMBDGroupCommentsModel;

    private GroupDetailAdapter adapter;

    public void refreshData(int flag) {
        Intent intent = getIntent();
        detail = (MBDGroupDetailModel) intent.getSerializableExtra("detail");
        adapter = new GroupDetailAdapter(detail);
        adapter.setItemClickListener(new GroupDetailAdapter.GroupDetailItemClickListener() {
            @Override
            public void onItemClick(MBDGroupCommentsModel commentsModel, int type, int position) {
                if (type == 1) {
                    mMBDGroupCommentsModel = commentsModel;
                    commentEt.setHint("回复 " + commentsModel.realName);
                    showInputMethodManager();
                } else {
                    //点赞
                    if (commentsModel.flag == 1) {
                        //一级评论点赞
                        commentLike(commentsModel, position);
                    } else {
                        //二级评论点赞
                        commentReplyLike(commentsModel, position);
                    }
                }
            }
        });
        MBDGroupDetailActivity.this.recyclerView.setAdapter(adapter);
        this.doGroupDetailRequest(detail.groupId, new MBDGroupDetailActivity.CallBack() {
            @Override
            public void completion(MBDGroupDetailModel detail) {
                if (detail != null) {
                    // 处理成功的响应
                    adapter.setGroupDetail(detail);
                    adapter.notifyDataSetChanged();
                    MBDGroupDetailActivity.this.doGroupCommontsRequest(detail.groupId, new CommentsRequestCallBack() {
                        @Override
                        public void completion(ArrayList<MBDGroupCommentsModel> commentsModels) {
                            detail.groupComments = commentsModels;
                            // 处理成功的响应
                            adapter.setGroupDetail(detail);
                            adapter.notifyDataSetChanged();
                            if (flag == 1) scrollToBottom();
                        }
                    });
                }
            }
        });
    }

    //快速排序

    private void doGroupDetailRequest(String groupId, MBDGroupDetailActivity.CallBack callBack) {
        assert !TextUtils.isEmpty(groupId);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("groupId", groupId);
        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_GROUP_GET_INFO, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    LinkedTreeMap<String, Object> linkedTreeMap = (LinkedTreeMap<String, Object>) response.data;
                    Gson gson = new Gson();
                    String jsonString = gson.toJson(linkedTreeMap);
                    MBDGroupDetailModel rst = gson.fromJson(jsonString, MBDGroupDetailModel.class);
                    callBack.completion(rst);
                } else {
                    Toast.makeText(MBDGroupDetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    private void doGroupCommontsRequest(String groupId, MBDGroupDetailActivity.CommentsRequestCallBack callBack) {
        assert !TextUtils.isEmpty(groupId);

        HashMap<String, String> params = new HashMap<String, String>();
        params.put("groupId", groupId);
        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_GROUP_COMMENT_LIST, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    ArrayList<LinkedTreeMap<String, Object>> comments = (ArrayList<LinkedTreeMap<String, Object>>) response.data;
                    ArrayList<MBDGroupCommentsModel> resultArray = new ArrayList<>();
                    for (int i = 0; i < comments.size(); i++) {
                        LinkedTreeMap<String, Object> linkedTreeMap = comments.get(i);
                        Gson gson = new Gson();
                        String jsonString = gson.toJson(linkedTreeMap);
                        MBDGroupCommentsModel rst = gson.fromJson(jsonString, MBDGroupCommentsModel.class);
                        rst.flag = 1;
                        resultArray.add(rst);
                        resultArray.addAll(rst.groupCommentReplyList);
                    }
                    callBack.completion(resultArray);
                } else {
                    Toast.makeText(MBDGroupDetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        });

    }

    private void sentComment() {
        assert !(null == detail);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("groupId", detail.groupId);
        params.put("comment", commentEt.getText().toString());
        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_GROUP_COMMENT_SAVE, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    mMBDGroupCommentsModel = null;
                    commentEt.setText("");
                    commentEt.setHint("写评论...");
                    refreshData(1);
                } else {
                    Toast.makeText(MBDGroupDetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private void sentCommentReply() {
        assert !(null == detail);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("groupId", detail.groupId);
        params.put("groupCommentId", mMBDGroupCommentsModel.groupCommentId);
        params.put("comment", commentEt.getText().toString());
        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_GROUP_COMMENT_REPLY_SAVE, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    mMBDGroupCommentsModel = null;
                    commentEt.setText("");
                    commentEt.setHint("写评论...");
                    refreshData(1);
                } else {
                    Toast.makeText(MBDGroupDetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private void like() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("groupId", detail.groupId);
        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_GROUP_LIKE, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    doGroupDetailRequest(detail.groupId, new MBDGroupDetailActivity.CallBack() {
                        @Override
                        public void completion(MBDGroupDetailModel detail) {
                            if (detail != null) {
                                likeIv.setAlpha(!StringUtils.isNull(detail.isLike) && detail.isLike.equals("1") ? 1f : 0.5f);
                            }
                        }
                    });

                }
            }
        });
    }

    private void commentLike(MBDGroupCommentsModel commentsModel, int position) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("groupCommentId", commentsModel.groupCommentId);
        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_GROUP_COMMENT_LIKE, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    if (commentsModel.isLike.equals("1")) {
                        commentsModel.isLike = "0";
                    } else {
                        commentsModel.isLike = "1";
                    }
                    adapter.notifyItemChanged(position);
                }
            }
        });
    }

    private void commentReplyLike(MBDGroupCommentsModel commentsModel, int position) {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("groupCommentReplyId", commentsModel.groupCommentReplyId);
        MBDHttpClient.shared().doRequest(ServiceType.SERVICE_GROUP_COMMENT_REPLY_LIKE, params, new MBDHttpClient.Callback() {
            @Override
            public void completion(boolean success, Error error, MBDModelResponse response) {
                if (success) {
                    if (commentsModel.isLike.equals("1")) {
                        commentsModel.isLike = "0";
                    } else {
                        commentsModel.isLike = "1";
                    }
                    adapter.notifyItemChanged(position);
                }
            }
        });
    }


    private void scrollToBottom() {
        int position = adapter.getItemCount() - 1;
        recyclerView.smoothScrollToPosition(position);
    }

    public interface CallBack {
        public void completion(MBDGroupDetailModel detail);
    }

    public interface CommentsRequestCallBack {
        public void completion(ArrayList<MBDGroupCommentsModel> commentsModel);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("Lifecycle", "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Lifecycle", "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d("Lifecycle", "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d("Lifecycle", "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("Lifecycle", "onDestroy");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d("Lifecycle", "onRestart");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.d("Lifecycle", "onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.d("Lifecycle", "onRestoreInstanceState");
    }
}
